package org.jeecg.modules.inspect.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.inspect.entity.InsClassesUnusualMsg;
import org.jeecg.modules.inspect.entity.InsClassesUnusualMsgCourse;
import org.jeecg.modules.inspect.entity.InsClassesUnusualMsgIssue;
import org.jeecg.modules.inspect.service.IInsClassesUnusualMsgCourseService;
import org.jeecg.modules.inspect.service.IInsClassesUnusualMsgIssueService;
import org.jeecg.modules.inspect.service.IInsClassesUnusualMsgService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

 /**
 * @Description: 异常信息
 * @Author: jeecg-boot
 * @Date:   2024-03-16
 * @Version: V1.0
 */
@Api(tags="异常信息")
@RestController
@RequestMapping("/inspect/insClassesUnusualMsg")
@Slf4j
public class InsClassesUnusualMsgController extends JeecgController<InsClassesUnusualMsg, IInsClassesUnusualMsgService> {

	@Autowired
	private IInsClassesUnusualMsgService insClassesUnusualMsgService;

	@Autowired
	private IInsClassesUnusualMsgIssueService insClassesUnusualMsgIssueService;

	@Autowired
	private IInsClassesUnusualMsgCourseService insClassesUnusualMsgCourseService;
	 @Autowired
	 private ISysUserService sysUserService;
	 @Autowired
	 private ISysDepartService sysDepartService;
	 @Autowired
	 private ISysUserDepartService sysUserDepartService;
	 @Autowired
	 private JdbcTemplate jdbcTemplate;

	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param insClassesUnusualMsg
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "异常信息-分页列表查询")
	@ApiOperation(value="异常信息-分页列表查询", notes="异常信息-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<InsClassesUnusualMsg>> queryPageList(InsClassesUnusualMsg insClassesUnusualMsg,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<InsClassesUnusualMsg> queryWrapper = QueryGenerator.initQueryWrapper(insClassesUnusualMsg, req.getParameterMap());
		Page<InsClassesUnusualMsg> page = new Page<InsClassesUnusualMsg>(pageNo, pageSize);
		IPage<InsClassesUnusualMsg> pageList = insClassesUnusualMsgService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	 /**
	  * 分页列表查询
	  * @param insClassesUnusualMsg
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "异常信息-分页列表查询")
	 @ApiOperation(value="异常信息-分页列表查询", notes="异常信息-分页列表查询")
	 @GetMapping(value = "/listReport")
	 public Result<IPage<InsClassesUnusualMsg>> queryPageListReport(InsClassesUnusualMsg insClassesUnusualMsg,
															  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
															  HttpServletRequest req) {
		 QueryWrapper<InsClassesUnusualMsg> queryWrapper = QueryGenerator.initQueryWrapper(insClassesUnusualMsg, req.getParameterMap());
		 Page<InsClassesUnusualMsg> page = new Page<InsClassesUnusualMsg>(pageNo, pageSize);
		 IPage<InsClassesUnusualMsg> pageList = insClassesUnusualMsgService.page(page, queryWrapper);

		 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		 String startTime = "";
		 String endTime = "";
		 String status = insClassesUnusualMsg.getStatus();
		 if(insClassesUnusualMsg.getStartDate()!=null){
			 startTime = format.format(insClassesUnusualMsg.getStartDate());
		 }
		 if(insClassesUnusualMsg.getEndDate()!=null){
			 endTime = format.format(insClassesUnusualMsg.getEndDate());
		 }
		 List<Map<String, Object>> listPage = jdbcTemplate.queryForList(
				 "select * from INS_CLASSES_UNUSUAL_MSG  where 1=1 " +
					 (StringUtils.isNotBlank(startTime)?" and date(create_time)>= '" + startTime +"'" :"" )+
					 (StringUtils.isNotBlank(endTime)?" and date(create_time)<= '" + endTime+"'" :"" )+
					 (StringUtils.isNotBlank(status)?" and status= " + status:"" )+
					 " order by create_time desc"+
				 	 " limit "+((pageNo-1)*pageSize)+","+pageSize);

		 Long count = jdbcTemplate.queryForObject(
				 "select count(0) from INS_CLASSES_UNUSUAL_MSG  where 1=1 " +
						 (StringUtils.isNotBlank(startTime)?" and date(create_time)>= '" + startTime+"'":"" )+
						 (StringUtils.isNotBlank(endTime)?" and date(create_time)<= '" + endTime+"'":"" ) +
						 (StringUtils.isNotBlank(status)?" and status= " + status:"" )
				 , Long.class);
		 List<InsClassesUnusualMsg> insClassesUnusualMsgs = JSONArray.parseArray(JSONArray.toJSONString(listPage), InsClassesUnusualMsg.class);
		 pageList.setRecords(insClassesUnusualMsgs);
		 pageList.setTotal(count);
		 return Result.OK(pageList);
	 }
	/**
     *   添加
     * @param insClassesUnusualMsg
     * @return
     */
    @AutoLog(value = "异常信息-添加")
    @ApiOperation(value="异常信息-添加", notes="异常信息-添加")
    //@RequiresPermissions("org.jeecg.modules:ins_classes_unusual_msg:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody InsClassesUnusualMsg insClassesUnusualMsg) {
        insClassesUnusualMsgService.save(insClassesUnusualMsg);
		//人员追溯
		List<InsClassesUnusualMsgCourse> courseList = insClassesUnusualMsg.getCourseList();
		if(CollectionUtils.isNotEmpty(courseList)){
			for (InsClassesUnusualMsgCourse course : courseList) {
				course.setUnusualId(insClassesUnusualMsg.getId());
				insClassesUnusualMsgCourseService.save(course);
			}
		}
		//问题表数据
		List<InsClassesUnusualMsgIssue> issueList = insClassesUnusualMsg.getIssueList();
		if(CollectionUtils.isNotEmpty(issueList)){
			for (InsClassesUnusualMsgIssue issue : issueList) {
				issue.setUnusualId(insClassesUnusualMsg.getId());
				insClassesUnusualMsgIssueService.save(issue);

			}
		}

		return Result.OK("添加成功！");
    }

    /**
     *  编辑
     * @param insClassesUnusualMsg
     * @return
     */
    @AutoLog(value = "异常信息-编辑")
    @ApiOperation(value="异常信息-编辑", notes="异常信息-编辑")
    //@RequiresPermissions("org.jeecg.modules:ins_classes_unusual_msg:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<String> edit(@RequestBody InsClassesUnusualMsg insClassesUnusualMsg) {
        insClassesUnusualMsgService.updateById(insClassesUnusualMsg);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "异常信息-通过id删除")
    @ApiOperation(value="异常信息-通过id删除", notes="异常信息-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:ins_classes_unusual_msg:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name="id",required=true) String id) {
        insClassesUnusualMsgService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @AutoLog(value = "异常信息-批量删除")
    @ApiOperation(value="异常信息-批量删除", notes="异常信息-批量删除")
    //@RequiresPermissions("org.jeecg.modules:ins_classes_unusual_msg:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.insClassesUnusualMsgService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     * @return
     */
    //@RequiresPermissions("org.jeecg.modules:ins_classes_unusual_msg:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, InsClassesUnusualMsg insClassesUnusualMsg) {
        return super.exportXls(request, insClassesUnusualMsg, InsClassesUnusualMsg.class, "异常信息");
    }

    /**
     * 导入
     * @return
     */
    //@RequiresPermissions("org.jeecg.modules:ins_classes_unusual_msg:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, InsClassesUnusualMsg.class);
    }
	/*---------------------------------主表处理-end-------------------------------------*/
	

    /*--------------------------------子表处理-异常问题-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	//@AutoLog(value = "异常问题-通过主表ID查询")
	@ApiOperation(value="异常问题-通过主表ID查询", notes="异常问题-通过主表ID查询")
	@GetMapping(value = "/listInsClassesUnusualMsgIssueByMainId")
    public Result<IPage<InsClassesUnusualMsgIssue>> listInsClassesUnusualMsgIssueByMainId(InsClassesUnusualMsgIssue insClassesUnusualMsgIssue,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<InsClassesUnusualMsgIssue> queryWrapper = QueryGenerator.initQueryWrapper(insClassesUnusualMsgIssue, req.getParameterMap());
        Page<InsClassesUnusualMsgIssue> page = new Page<InsClassesUnusualMsgIssue>(pageNo, pageSize);
        IPage<InsClassesUnusualMsgIssue> pageList = insClassesUnusualMsgIssueService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param insClassesUnusualMsgIssue
	 * @return
	 */
	@AutoLog(value = "异常问题-添加")
	@ApiOperation(value="异常问题-添加", notes="异常问题-添加")
	@PostMapping(value = "/addInsClassesUnusualMsgIssue")
	public Result<String> addInsClassesUnusualMsgIssue(@RequestBody InsClassesUnusualMsgIssue insClassesUnusualMsgIssue) {
		insClassesUnusualMsgIssueService.save(insClassesUnusualMsgIssue);
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param insClassesUnusualMsgIssue
	 * @return
	 */
	@AutoLog(value = "异常问题-编辑")
	@ApiOperation(value="异常问题-编辑", notes="异常问题-编辑")
	@RequestMapping(value = "/editInsClassesUnusualMsgIssue", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> editInsClassesUnusualMsgIssue(@RequestBody InsClassesUnusualMsgIssue insClassesUnusualMsgIssue) {
		insClassesUnusualMsgIssueService.updateById(insClassesUnusualMsgIssue);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "异常问题-通过id删除")
	@ApiOperation(value="异常问题-通过id删除", notes="异常问题-通过id删除")
	@DeleteMapping(value = "/deleteInsClassesUnusualMsgIssue")
	public Result<String> deleteInsClassesUnusualMsgIssue(@RequestParam(name="id",required=true) String id) {
		insClassesUnusualMsgIssueService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "异常问题-批量删除")
	@ApiOperation(value="异常问题-批量删除", notes="异常问题-批量删除")
	@DeleteMapping(value = "/deleteBatchInsClassesUnusualMsgIssue")
	public Result<String> deleteBatchInsClassesUnusualMsgIssue(@RequestParam(name="ids",required=true) String ids) {
	    this.insClassesUnusualMsgIssueService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportInsClassesUnusualMsgIssue")
    public ModelAndView exportInsClassesUnusualMsgIssue(HttpServletRequest request, InsClassesUnusualMsgIssue insClassesUnusualMsgIssue) {
		 // Step.1 组装查询条件
		 QueryWrapper<InsClassesUnusualMsgIssue> queryWrapper = QueryGenerator.initQueryWrapper(insClassesUnusualMsgIssue, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<InsClassesUnusualMsgIssue> pageList = insClassesUnusualMsgIssueService.list(queryWrapper);
		 List<InsClassesUnusualMsgIssue> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, "异常问题");
		 mv.addObject(NormalExcelConstants.CLASS, InsClassesUnusualMsgIssue.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("异常问题报表", "导出人:" + sysUser.getRealname(), "异常问题"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importInsClassesUnusualMsgIssue/{mainId}")
    public Result<?> importInsClassesUnusualMsgIssue(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
       // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<InsClassesUnusualMsgIssue> list = ExcelImportUtil.importExcel(file.getInputStream(), InsClassesUnusualMsgIssue.class, params);
				 for (InsClassesUnusualMsgIssue temp : list) {
                    temp.setUnusualId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 insClassesUnusualMsgIssueService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-异常问题-end----------------------------------------------*/

    /*--------------------------------子表处理-异常历史追溯-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	//@AutoLog(value = "异常历史追溯-通过主表ID查询")
	@ApiOperation(value="异常历史追溯-通过主表ID查询", notes="异常历史追溯-通过主表ID查询")
	@GetMapping(value = "/listInsClassesUnusualMsgCourseByMainId")
    public Result<IPage<InsClassesUnusualMsgCourse>> listInsClassesUnusualMsgCourseByMainId(InsClassesUnusualMsgCourse insClassesUnusualMsgCourse,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<InsClassesUnusualMsgCourse> queryWrapper = QueryGenerator.initQueryWrapper(insClassesUnusualMsgCourse, req.getParameterMap());
        Page<InsClassesUnusualMsgCourse> page = new Page<InsClassesUnusualMsgCourse>(pageNo, pageSize);
        IPage<InsClassesUnusualMsgCourse> pageList = insClassesUnusualMsgCourseService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param insClassesUnusualMsgCourse
	 * @return
	 */
	@AutoLog(value = "异常历史追溯-添加")
	@ApiOperation(value="异常历史追溯-添加", notes="异常历史追溯-添加")
	@PostMapping(value = "/addInsClassesUnusualMsgCourse")
	public Result<String> addInsClassesUnusualMsgCourse(@RequestBody InsClassesUnusualMsgCourse insClassesUnusualMsgCourse) {
		insClassesUnusualMsgCourseService.save(insClassesUnusualMsgCourse);
		//修改主表状态
		insClassesUnusualMsgService.updateUnusualStatusById(insClassesUnusualMsgCourse.getUnusualId());
		//给当前责任人下发短信
		String unusualRecipientId = insClassesUnusualMsgCourse.getUnusualRecipientId();
		insClassesUnusualMsgService.sendSMS(Arrays.asList(new String[]{unusualRecipientId}));
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param insClassesUnusualMsgCourse
	 * @return
	 */
	@AutoLog(value = "异常历史追溯-编辑")
	@ApiOperation(value="异常历史追溯-编辑", notes="异常历史追溯-编辑")
	@RequestMapping(value = "/editInsClassesUnusualMsgCourse", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> editInsClassesUnusualMsgCourse(@RequestBody InsClassesUnusualMsgCourse insClassesUnusualMsgCourse) {
		insClassesUnusualMsgCourseService.updateById(insClassesUnusualMsgCourse);
		//修改主表状态
		insClassesUnusualMsgService.updateUnusualStatusById(insClassesUnusualMsgCourse.getUnusualId());
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "异常历史追溯-通过id删除")
	@ApiOperation(value="异常历史追溯-通过id删除", notes="异常历史追溯-通过id删除")
	@DeleteMapping(value = "/deleteInsClassesUnusualMsgCourse")
	public Result<String> deleteInsClassesUnusualMsgCourse(@RequestParam(name="id",required=true) String id) {
		InsClassesUnusualMsgCourse msgCourse = insClassesUnusualMsgCourseService.getById(id);
		insClassesUnusualMsgCourseService.removeById(id);
		//修改主表状态
		insClassesUnusualMsgService.updateUnusualStatusById(msgCourse.getUnusualId());
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "异常历史追溯-批量删除")
	@ApiOperation(value="异常历史追溯-批量删除", notes="异常历史追溯-批量删除")
	@DeleteMapping(value = "/deleteBatchInsClassesUnusualMsgCourse")
	public Result<String> deleteBatchInsClassesUnusualMsgCourse(@RequestParam(name="ids",required=true) String ids) {
		List<InsClassesUnusualMsgCourse> msgCourses = insClassesUnusualMsgCourseService.listByIds(Arrays.asList(ids.split(",")));
		this.insClassesUnusualMsgCourseService.removeByIds(Arrays.asList(ids.split(",")));
		//修改主表状态
		for (InsClassesUnusualMsgCourse msgCours : msgCourses) {
			insClassesUnusualMsgService.updateUnusualStatusById(msgCours.getUnusualId());
		}
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportInsClassesUnusualMsgCourse")
    public ModelAndView exportInsClassesUnusualMsgCourse(HttpServletRequest request, InsClassesUnusualMsgCourse insClassesUnusualMsgCourse) {
		 // Step.1 组装查询条件
		 QueryWrapper<InsClassesUnusualMsgCourse> queryWrapper = QueryGenerator.initQueryWrapper(insClassesUnusualMsgCourse, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<InsClassesUnusualMsgCourse> pageList = insClassesUnusualMsgCourseService.list(queryWrapper);
		 List<InsClassesUnusualMsgCourse> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, "异常历史追溯");
		 mv.addObject(NormalExcelConstants.CLASS, InsClassesUnusualMsgCourse.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("异常历史追溯报表", "导出人:" + sysUser.getRealname(), "异常历史追溯"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importInsClassesUnusualMsgCourse/{mainId}")
    public Result<?> importInsClassesUnusualMsgCourse(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
       // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<InsClassesUnusualMsgCourse> list = ExcelImportUtil.importExcel(file.getInputStream(), InsClassesUnusualMsgCourse.class, params);
				 for (InsClassesUnusualMsgCourse temp : list) {
                    temp.setUnusualId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 insClassesUnusualMsgCourseService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-异常历史追溯-end----------------------------------------------*/

	 /**
	  * 根据当前登陆人ID查询异常信息
	  * @Param type unusualRecipient:责任人;unusualInitiator:发起人
	  * @return
	  */
	 @GetMapping(value = "/queryIssueByUserId")
	 public Result<List<InsClassesUnusualMsg>> queryIssueByUserId(String type) {
		 Result<List<InsClassesUnusualMsg>> result = new Result<>();
		 //查询当前登录人
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 List<InsClassesUnusualMsgCourse> coursess = insClassesUnusualMsgCourseService.list();
		 if(CollectionUtils.isNotEmpty(coursess)){
			 //发起人过滤  查询发起人数据不判断状态
			 if("unusualInitiator".equals(type)){
				 coursess = coursess.stream().filter(o-> user.getUsername().equals(o.getUnusualInitiatorId())).collect(Collectors.toList());
			 }else{ //责任人过滤
				 coursess = coursess.stream().filter(o->("1".equals(o.getStatus()) || "0".equals(o.getStatus())) && user.getUsername().equals(o.getUnusualRecipientId())).collect(Collectors.toList());
			 }
		 }
		 //过滤出全部主表数据
		 if(CollectionUtils.isNotEmpty(coursess)){
			 List<SysUser> users = sysUserService.list();
			 Map<String, String> userValue = users.stream().collect(Collectors.toMap(o -> o.getUsername(), o -> o.getRealname(), (p, e) -> e));
			 for (InsClassesUnusualMsgCourse course : coursess) {
				 course.setUnusualInitiator_dictText(userValue.get(course.getUnusualInitiatorId()));
				 course.setUnusualRecipient_dictText(userValue.get(course.getUnusualRecipientId()));
			 }
			 List<String> unusualIds = coursess.stream().map(o -> o.getUnusualId()).collect(Collectors.toSet()).stream().collect(Collectors.toList());
			 //根据主表ID查询全部主表数据
			 List<InsClassesUnusualMsg> unusualMsgs = insClassesUnusualMsgService.listByIds(unusualIds);
			 //查询出全部问题数据
			 List<InsClassesUnusualMsgIssue> issues = insClassesUnusualMsgIssueService.list();
			 List<InsClassesUnusualMsgCourse> courses = insClassesUnusualMsgCourseService.list();
			 for (InsClassesUnusualMsg unusualMsg : unusualMsgs) {
				 String unusualId = unusualMsg.getId();

				 //处理过滤异常问题数据
				 List<InsClassesUnusualMsgIssue> issuesList = new ArrayList<>();
				 if(CollectionUtils.isNotEmpty(issues)){
					 issuesList = issues.stream().filter(o->unusualId.equals(o.getUnusualId())).collect(Collectors.toList());
				 }
				 if(CollectionUtils.isNotEmpty(issuesList)){
					 unusualMsg.setIssueList(issuesList);
				 }else{
					 unusualMsg.setIssueList(new ArrayList<>());
				 }

				 //处理过滤异常追溯数据
				 List<InsClassesUnusualMsgCourse> courseList = new ArrayList<>();
				 if(CollectionUtils.isNotEmpty(courses)){
					 courseList = courses.stream().filter(o->unusualId.equals(o.getUnusualId())).collect(Collectors.toList());
				 }
				 if(CollectionUtils.isNotEmpty(courseList)){
					 unusualMsg.setCourseList(courseList);
				 }else{
					 unusualMsg.setCourseList(new ArrayList<>());
				 }
			 }
			 Collections.sort(unusualMsgs, new Comparator<InsClassesUnusualMsg>() {
				 @Override
				 public int compare(InsClassesUnusualMsg o1, InsClassesUnusualMsg o2) {
					 return o2.getCreateTime().compareTo(o1.getCreateTime());
				 }
			 });
			 if(unusualMsgs.size()>100){
				 unusualMsgs = unusualMsgs.subList(0,100);
			 }
			 result.setResult(unusualMsgs);
		 }else{
			 result.setResult(new ArrayList<InsClassesUnusualMsg>());
		 }
		 return result;
	 }

	 /**
	  * 根据当前登陆人ID查询异常信息
	  * @Param type unusualRecipient:责任人;unusualInitiator:发起人
	  * @return
	  */
	 @GetMapping(value = "/queryIssueByUserIdSearch")
	 public Result<IPage<InsClassesUnusualMsg>> queryIssueByUserIdSearch(
			 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			 @RequestParam(name="timeStart", defaultValue="") String timeStart,
			 @RequestParam(name="timeEnd", defaultValue="") String timeEnd,
			 @RequestParam(name="deptCode", defaultValue="") String deptCode,
			 HttpServletRequest request) {

		 QueryWrapper<InsClassesUnusualMsg> queryWrapper = QueryGenerator.initQueryWrapper(new InsClassesUnusualMsg() , request.getParameterMap());
		 queryWrapper.orderByDesc("create_time");
		 // 添加时间范围条件
		 if(StringUtils.isNotBlank(timeStart)){
			 queryWrapper.ge("create_time", timeStart);
		 }
		 if(StringUtils.isNotBlank(timeEnd)){
			 queryWrapper.le("create_time", timeEnd);
		 }
		 if(StringUtils.isNotBlank(deptCode)){
			 //通过部门查询部门下全部用户
			 List<SysUser> sysUsers = sysUserDepartService.queryUserByDepCode(deptCode, "");
			 if(CollectionUtils.isNotEmpty(sysUsers)){
				 List<String> names = sysUsers.stream().map(o -> o.getUsername()).collect(Collectors.toList());
				 if(CollectionUtils.isNotEmpty(names)){
					 queryWrapper.in("create_by", names);
				 }
			 }
		 }
		 Page<InsClassesUnusualMsg> page = new Page<InsClassesUnusualMsg>(pageNo, pageSize);
		 IPage<InsClassesUnusualMsg> pageList = insClassesUnusualMsgService.page(page, queryWrapper);
		 List<InsClassesUnusualMsg> unusualMsgs = pageList.getRecords();

		 //过滤出全部主表数据
		 if(CollectionUtils.isNotEmpty(unusualMsgs)){
			 List<SysUser> users = sysUserService.list();
			 Map<String, String> userValue = users.stream().collect(Collectors.toMap(o -> o.getUsername(), o -> o.getRealname(), (p, e) -> e));
			 //查询出全部问题数据
			 for (InsClassesUnusualMsg unusualMsg : unusualMsgs) {
				 String unusualId = unusualMsg.getId();

				 List<InsClassesUnusualMsgIssue> issues = insClassesUnusualMsgIssueService.list(Wrappers.<InsClassesUnusualMsgIssue>lambdaQuery().eq(InsClassesUnusualMsgIssue::getUnusualId, unusualId));
				 List<InsClassesUnusualMsgCourse> courses = insClassesUnusualMsgCourseService.list(Wrappers.<InsClassesUnusualMsgCourse>lambdaQuery().eq(InsClassesUnusualMsgCourse::getUnusualId, unusualId));
				 //处理过滤异常问题数据
				 List<InsClassesUnusualMsgIssue> issuesList = new ArrayList<>();
				 if(CollectionUtils.isNotEmpty(issues)){
					 issuesList = issues.stream().filter(o->unusualId.equals(o.getUnusualId())).collect(Collectors.toList());
				 }
				 if(CollectionUtils.isNotEmpty(issuesList)){
					 unusualMsg.setIssueList(issuesList);
				 }else{
					 unusualMsg.setIssueList(new ArrayList<>());
				 }


				 //处理过滤异常追溯数据
				 List<InsClassesUnusualMsgCourse> courseList = new ArrayList<>();
				 if(CollectionUtils.isNotEmpty(courses)){
					 courseList = courses.stream().filter(o->unusualId.equals(o.getUnusualId())).collect(Collectors.toList());
					 for (InsClassesUnusualMsgCourse course : courses) {
						 course.setUnusualInitiator_dictText(userValue.get(course.getUnusualInitiatorId()));
						 course.setUnusualRecipient_dictText(userValue.get(course.getUnusualRecipientId()));
					 }
				 }
				 if(CollectionUtils.isNotEmpty(courseList)){
					 unusualMsg.setCourseList(courseList);
				 }else{
					 unusualMsg.setCourseList(new ArrayList<>());
				 }
			 }
			 pageList.setRecords(unusualMsgs);
		 }else{
			 pageList.setRecords(new ArrayList<InsClassesUnusualMsg>());
		 }
		 return Result.OK(pageList);

	 }


	 @Resource
	 private ISysBaseAPI sysBaseApi;

	 /**
	  * 根据当前登陆人查询负责部门异常数据
	  * @return
	  */
	 @RequestMapping("queryMsgByLoginUserQDeptAuthor")
	 public Result<List<InsClassesUnusualMsg>> queryMsgByLoginUserQDeptAuthor() {
		 Result<List<InsClassesUnusualMsg>> result = new Result<>();
		 //查询当前登录人
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 String username = user.getUsername();
		 //根据部门 负责人查询部门
		 String deptIdsStr = jdbcTemplate.queryForObject("select depart_ids as \"id\" from sys_user where username='"+username+"'",String.class);
		 if (StringUtils.isNotBlank(deptIdsStr)) {
			 List<String> deptIds = Arrays.asList(deptIdsStr.split(","));
			 List<String> userNames = new ArrayList<>();
			 for (String deptId : deptIds) {
				 //通过部门查询部门下全部用户
				 List<String> names = sysBaseApi.getUserByDeptId(deptId);
				 if(CollectionUtils.isNotEmpty(names)){
					 userNames.addAll(names);
                 }
			 }
			 List<InsClassesUnusualMsg> msgs = insClassesUnusualMsgService.list();
			 msgs = msgs.stream().filter(o->userNames.contains(o.getCreateBy())).collect(Collectors.toList());
			 //查询出全部问题数据
			 List<InsClassesUnusualMsgIssue> issues = insClassesUnusualMsgIssueService.list();
			 List<InsClassesUnusualMsgCourse> courses = insClassesUnusualMsgCourseService.list();
			 for (InsClassesUnusualMsg msg : msgs) {
				 List<InsClassesUnusualMsgIssue> issuesList = new ArrayList<>();
				 List<InsClassesUnusualMsgCourse> courseList = new ArrayList<>();
				 String unusualId = msg.getId();
				 List<InsClassesUnusualMsgIssue> msgIssues = issues.stream().filter(o -> unusualId.equals(o.getUnusualId())).collect(Collectors.toList());
				 if(CollectionUtils.isNotEmpty(msgIssues)){
					 issuesList.addAll(msgIssues);
				 }
				 List<InsClassesUnusualMsgCourse> coursesList = courses.stream().filter(o -> unusualId.equals(o.getUnusualId())).collect(Collectors.toList());
				 if(CollectionUtils.isNotEmpty(coursesList)){
					 courseList.addAll(coursesList);
				 }
				 msg.setIssueList(issuesList);
				 msg.setCourseList(courseList);
			 }
			 result.setResult(msgs);
		 }
		 return result;
	 }


	 /**
	  * 查询问题报表
	  * @return
	  */
	 @RequestMapping("queryMsgIssueReport")
	 public Result<IPage<Map<String,Object>>> queryMsgIssueReport(@RequestParam(name="departIds",required = false)String deptIds,
																  @RequestParam(name="insTime_begin",required = false)String insTime_begin,
																  @RequestParam(name="insTime_end",required = false)String insTime_end,
																  @RequestParam(name="createBy",required = false)String createBy,
																  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		 Result<IPage<Map<String, Object>>> result = new Result<>();
		 Page<Map<String, Object>> page = new Page<>(pageNo, pageSize);


		 List<Map<String,Object>> msgIssueLists = jdbcTemplate.queryForList(
				 " SELECT " +
					 " i.id as \"id\", " +
					 " i.unusual_id as \"unusualId\", " +
					 " i.remark as \"remark\", " +
					 " i.create_by as \"createBy\", " +
					 " i.create_time as \"createTime\", " +
					 " i.issue_desc as \"issueDesc\", " +
					 " if(m.STATUS='1','处理中','已解决') AS \"status\" , " +
					 " u.realname as \"createByName\", " +
					 " d.id as \"deptId\", " +
					 " d.depart_name as \"deptName\" " +
					 " FROM " +
					 " ins_classes_unusual_msg_issue i " +
					 " LEFT JOIN ins_classes_unusual_msg m ON m.id = i.unusual_id  " +
					 " left join sys_user u on u.username=i.create_by " +
					 " left join sys_user_depart ud on ud.user_id=u.id " +
					 " left join sys_depart d on d.id=ud.dep_id " +
					 " where 1=1 " +
						 (StringUtils.isNotBlank(deptIds) ? " and instr('" + deptIds + "', d.id)>0 " : "") +
						 (StringUtils.isNotBlank(insTime_begin) ? " and DATE_FORMAT( i.create_time, '%Y-%m-%d' )>='" + insTime_begin + "' " : "") +
						 (StringUtils.isNotBlank(insTime_end) ? " and DATE_FORMAT( i.create_time, '%Y-%m-%d' )<='" + insTime_end + "' " : "") +
						 (StringUtils.isNotBlank(createBy) ? " and u.realname like '%" + createBy + "%' " : "") +
					 " ORDER BY " +
					 " d.depart_name, " +
					 " i.create_time DESC, " +
					 " i.create_by " +
					 (pageNo != null && pageSize != null ? " limit " + (pageNo - 1) * pageSize + "," + pageSize : ""));
		 Long count = jdbcTemplate.queryForObject(
				 " SELECT  count(0)  FROM   ins_classes_unusual_msg_issue i " +
						 " LEFT JOIN ins_classes_unusual_msg m ON m.id = i.unusual_id  " +
						 " left join sys_user u on u.username=i.create_by " +
						 " left join sys_user_depart ud on ud.user_id=u.id " +
						 " left join sys_depart d on d.id=ud.dep_id  where 1=1 " +
							 ( StringUtils.isNotBlank(deptIds)?" and instr('"+deptIds+"', d.id)>0 " :"")+
							 ( StringUtils.isNotBlank(insTime_begin)?" and DATE_FORMAT( i.create_time, '%Y-%m-%d' )>='"+insTime_begin+"' " :"")+
							 ( StringUtils.isNotBlank(insTime_end)?" and DATE_FORMAT( i.create_time, '%Y-%m-%d' )<='"+insTime_end+"' " :"")+
							 ( StringUtils.isNotBlank(createBy)?" and u.realname like '%"+createBy+"%' " :"")+
						 " ORDER BY   d.depart_name,   i.create_time DESC,   i.create_by "
				 , Long.class);
		 page.setTotal(count);
		 page.setRecords(msgIssueLists);
		 result.setResult(page);
		 return result;
	 }

}
